<template>
  <div id="unitInformation">
    <div class="pageMain">
      <el-form :model="unitForm" :rules="unitRules" ref="unitForm" label-width="110px" class="unitForm">
        <div class="formHead">
          <span>企业信息</span>
          <i v-if="jurisdictionControl.J_edit && !isEdit" class="iconfont iconsize" @click="isEdit = true">&#xe631;</i>
          <div class="pageFooter" v-if="isEdit">
            <el-button size="medium" round @click="cancelSave">取 消</el-button>
            <el-button size="medium" type="primary" round :loading="isConfirmLoading1" style="margin-left: 30px" @click="saveUnitInfo">保 存</el-button>
          </div>
        </div>
        <div class="formheader">
          <el-form-item label="企业号：">
            <p>{{ unitForm.companynumber }}</p>
          </el-form-item>
          <el-form-item label="注册手机号：">
            <p>{{ unitForm.phone }}</p>
          </el-form-item>
          <el-form-item label="注册日期：">
            <p>{{ unitForm.createTime }}</p>
          </el-form-item>
        </div>
        <el-form-item label="单位名称：" prop="companyname">
          <el-input v-if="isEdit" v-model="unitForm.companyname" placeholder="单位名称"></el-input>
          <p v-else>{{ unitForm.companyname }}</p>
        </el-form-item>
        <el-form-item label="地址：" prop="addressAllId">
          <el-cascader v-if="isEdit" :options="cityList" v-model="unitForm.addressAllId" :props="defaultProps"></el-cascader>
          <p v-else>{{ unitForm.fullAddress }}</p>
        </el-form-item>
        <el-form-item label="详细地址：" v-if="isEdit">
          <el-input type="textarea" v-model="unitForm.address" style="width: 450px" placeholder="详细地址"></el-input>
        </el-form-item>

        <div class="formFooter">
          <el-form-item label="邮箱：" prop="email">
            <el-input v-if="isEdit" v-model="unitForm.email" placeholder="邮箱"></el-input>
            <p v-else>{{ unitForm.email }}</p>
          </el-form-item>
          <el-form-item label="登录方式：" prop="loginType">
            <el-select v-if="isEdit" v-model="unitForm.loginType" placeholder="登录方式">
              <el-option label="账号+密码" :value="0"></el-option>
              <!-- <el-option label="账号+密码+加密狗" :value="1"></el-option> -->
            </el-select>
            <p v-else>{{ unitForm.loginType == 0 ? "账号+密码" : "账号+密码+加密狗" }}</p>
          </el-form-item>
          <el-form-item label="所属行业：" prop="industryid">
            <el-select v-model="unitForm.industryid" clearable filterable v-if="isEdit">
              <el-option v-for="item in industryList" :key="item.id" :label="item.industryName" :value="item.id"></el-option>
            </el-select>
            <p v-else>{{ !unitForm.industryid ? "未设置" : industryList.find((item) => item.id == unitForm.industryid)?.industryName }}</p>
          </el-form-item>
        </div>
      </el-form>
      <el-form :model="unitForm1" :rules="unitRules1" ref="unitForm1" label-width="150px" class="unitForm">
        <div class="formHead">
          <span>管理员信息</span>
          <i v-if="jurisdictionControl.J_editUser && !isEdit1" class="iconfont iconsize" @click="isEdit1 = true">&#xe631;</i>
          <div class="pageFooter" v-if="isEdit1">
            <el-button size="medium" round @click="cancelSave1">取 消</el-button>
            <el-button size="medium" type="primary" round :loading="isConfirmLoading" style="margin-left: 30px" @click="saveAdminMessage">保 存</el-button>
          </div>
        </div>
        <el-form-item label="管理员所在企业" prop="AllId">
          <el-cascader ref="cascader" :disabled="!isEdit1" :options="companySection" v-model="unitForm1.AllId" :props="defaultProps1" popper-class="popper_person"></el-cascader>
          <!-- <p v-else>{{ unitForm1.fullAddress }}</p> -->
        </el-form-item>
        <el-form-item label="姓名：" prop="realName">
          <p>{{ unitForm1.realName }}</p>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <p>{{ unitForm1.phone }}</p>
        </el-form-item>
      </el-form>

      <!-- <el-form label-width="40px" class="unitForm">
        <div class="formHead">
          <span>安全设置</span>
        </div>
        <el-form-item label="">
          <p>在页面上开启水印显示,已防止截屏泄密,水印范围：ERP所有模块功能,水印内容：姓名+手机号</p>
          <p>安全水印：<el-switch v-model="watermark" active-color="#13ce66" @change="onchangewatermark"> </el-switch></p>
        </el-form-item>
      </el-form> -->
    </div>
  </div>
</template>

<script>
import * as Vrules from "@/util/validate";
import { mapState } from "vuex";
import { mixinsMethod } from "@/util/util";
import { quitFun } from "@/util/quit";
export default {
  name: "unitInformation",
  data() {
    return {
      watermark: false,
      industryList: [],
      unitForm: {
        createTime: "", //创建时间
        companyid: "", //公司ids
        companynumber: "", //企业号
        ompanyname: "", //企业名称
        companylogo: "", //logo
        type: "", //注册类型：0为中小企业
        email: "", //邮箱
        code: "", //销售码
        industryid: "",
        province: "", //省份
        city: "", //市
        area: "", //县
        serviceStartDate: "", //服务开始时间
        serviceEndDate: "", //服务结束日期
        accountCount: "", //账套总数
        accountSurplusCount: "", //账套剩余数量
        address: "", //地址
        phone: "", //手机号
        loginType: "", //登录类型 0:账号密码；1为加密狗+账号密码
        fileSpaceSize: "", // 空间 kb
        fileSpaceSurplusSize: "", //剩余空间 kb
        pwd: "", //注册时密码
      },
      unitForm1: {
        AllId: [],
      },
      isConfirmLoading: false,
      isConfirmLoading1: false,
      isEdit: false,
      isEdit1: false,
      defaultProps: {
        children: "children",
        label: "name",
        value: "areaID",
      },
      jurisdictionControl: {
        J_edit: false,
        J_editUser: false,
      },
      SubCompany: [], // 公司部门
      unitRules: {
        companyname: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
        addressAllId: [{ required: true, message: "请输入单位地址", trigger: "change" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: Vrules.isEmail, trigger: "change" },
        ],
        industryid: [{ required: true, message: "请选择所属行业", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: Vrules.isPhone, trigger: "change" },
        ],
      },
      defaultProps1: {
        children: "childrens",
        label: "name",
        value: "id",
        checkStrictly: true,
      },
      AdminData: "",
      SetData: "",
      SetData1: [],
      AllId: [],
      unitRules1: {
        AllId: [{ required: true, message: "请输入单位地址", trigger: "change" }],
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.common.userInfo,
      moduleId: (state) => state.common.moduleId,
      cityList: (state) => state.common.provinceCityList,
      companySection: (state) => state.common.companySection,
    }),
  },
  methods: {
    onchangewatermark() {
      let params = {
        industryid: this.userInfo.industryid,
        isOpenWatermark: this.watermark,
      };
      this.$api.publicApi
        .EditIndustryOrWatermark(params)
        .then((res) => {
          let { data, message, status } = res.data;
          if (status == 200) {
            this.dialogVisible = false;
            this.userInfo.isOpenWatermark = params.isOpenWatermark;
            this.$store.dispatch("GetUserInfo", this.userInfo);
            this.$bus.$emit("GetisWork", this.userInfo.isOpenWatermark);
          }
        })
        .catch(() => {});
    },
    getUnitInfo() {
      // 获取单位信息
      this.$api.systemManagement.GetInfo().then((res) => {
        let resData = res.data.data;
        this.unitForm = resData;
        this.unitForm.addressAllId = resData.area ? [resData.province, resData.city, resData.area] : [resData.province, resData.city];
        let fullAddress = "";
        this.cityList.map((item) => {
          if (item.areaID == resData.province) {
            fullAddress += item.name;
            item.children.map((items) => {
              if (items.areaID == resData.city) {
                fullAddress += items.name;
                if (items.children && items.children.length != 0) {
                  items.children.map((itemss) => {
                    if (itemss.areaID == resData.area) {
                      fullAddress += itemss.name;
                    }
                  });
                }
              }
            });
          }
        });
        if (fullAddress.slice(0, 3) == fullAddress.slice(3, 6)) {
          fullAddress = fullAddress.slice(3);
        }
        if (fullAddress.slice(0, 7) == fullAddress.slice(7, 14)) {
          fullAddress = fullAddress.slice(7);
        }
        this.unitForm.fullAddress = fullAddress + "" + (resData.address ? resData.address : "");
      });
    },
    onEditIndustry() {
      let params = {
        industryid: this.unitForm.industryid,
        isOpenWatermark: this.userInfo.isOpenWatermark,
      };
      this.$api.publicApi
        .EditIndustryOrWatermark(params)
        .then((res) => {
          let { data, message, status } = res.data;
          if (status == 200) {
            this.userInfo.industryid = params.industryid;
            this.$store.dispatch("GetUserInfo", this.userInfo);
          }
        })
        .catch(() => {});
    },
    saveUnitInfo() {
      // 保存
      this.$refs["unitForm"].validate((valid) => {
        if (valid) {
          this.isConfirmLoading1 = true;
          let params = {
            companyid: this.unitForm.companyid,
            province: this.unitForm.addressAllId[0],
            city: this.unitForm.addressAllId[1],
            area: this.unitForm.addressAllId[2],
            companyname: this.unitForm.companyname,
            address: this.unitForm.address,
            email: this.unitForm.email,
            loginType: this.unitForm.loginType,
          };
          this.onEditIndustry();
          this.$api.systemManagement
            .GetInfoEdit(params)
            .then((res) => {
              this.isEdit = false;
              this.isConfirmLoading1 = false;
              if (res.data.status == 200) {
                this.$message({ message: "修改成功", type: "success" });
                this.getUnitInfo();
              }
            })
            .catch(() => {
              this.isConfirmLoading1 = false;
            });
        }
      });
    },
    cancelSave() {
      this.isEdit = false;
      this.$refs.unitForm.clearValidate();
      this.getUnitInfo();
    },
    getindustryidList() {
      this.$api.publicApi
        .GetCompanyIndustryTemp()
        .then((res) => {
          let { data, message, status } = res.data;
          if (status == 200) this.industryList = data;
        })
        .catch(() => {});
    },
    getJurisdiction() {
      // 获取权限数据
      if (this.userInfo.isadmin) {
        this.jurisdictionControl = {
          J_edit: true,
          J_editUser: true,
        };
        return;
      }
      this.$api.publicApi.GetActionInfo({ id: this.moduleId }).then((res) => {
        let resData = res.data.data;
        resData.map((item) => {
          if (item.name === "修改企业信息") this.jurisdictionControl.J_edit = true;
          if (item.name === "修改管理员信息") this.jurisdictionControl.J_editUser = true;
        });
      });
    },

    getAdminMessage() {
      // 获取管理员信息
      if (!this.companySection || this.companySection.length == 0) {
        this.$message({ message: "暂无存在部门的企业", type: "warning" });
      }
      this.$api.systemManagement.GetManagerInfo().then((res) => {
        if (res.data.status == 200) {
          let resData = res.data.data;
          this.AdminData = res.data.data;
          this.unitForm1 = {
            fullAddress: "",
            AllId: [],
            ...resData,
          };
          let data = this.getAllId(this.companySection, resData.departmentid);
          while (data?.type) {
            this.unitForm1.AllId.splice(0, 0, data?.id);
            data = this.getAllId(this.companySection, data?.parentId);
          }
          // this.unitForm1.AllId.splice(0, 0, data?.id);
          // this.initialize(this.companySection, "1");
          // if (this.SetData) {
          //   this.SetData1.map((item) => {
          //     // this.unitForm1.fullAddress += item.name + '/';
          //     this.unitForm1.AllId.push(item.id);
          //   });
          //   this.AllId = JSON.parse(JSON.stringify(this.unitForm1.AllId));
          //   // this.unitForm1.fullAddress = this.unitForm1.fullAddress.slice(0, this.unitForm1.fullAddress.length - 1);
          // }
        }
      });
    },
    getAllId(data, id) {
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (item.id == id) {
          return item;
        }
        if (item?.childrens?.length) {
          const tempData = this.getAllId(item.childrens, id);
          if (tempData) return tempData;
        }
      }
    },
    initialize(arr = [], type) {
      for (let i = 0; i < arr.length; i++) {
        if (this.SetData) return;
        if (type == 1) {
          this.SetData1 = [];
        }
        const item = arr[i];
        this.SetData1.push(item);
        if (item.id == this.AdminData.subid) item.disabled = true;
        if (item?.childrens?.length) this.initialize(item.childrens);
        else {
          // 底层
          if (item.id == this.unitForm1.departmentid) {
            // 底层id
            this.SetData = item;
            return;
          } else {
            this.SetData1.pop();
          }
        }
      }
    },

    // 管理员信息
    cancelSave1() {
      this.isEdit1 = false;

      this.$refs.unitForm1.clearValidate();
      this.unitForm1.AllId = this.AllId;
      // this.getAdminMessage();
    },
    saveAdminMessage() {
      this.$refs["unitForm1"].validate((valid) => {
        if (valid) {
          let params = {
            userId: this.AdminData.userid,
            departmentId: this.unitForm1.AllId[this.unitForm1.AllId.length - 1],
            subId: this.unitForm1.AllId[0],
            oldSubId: this.AdminData.subid,
          };
          if (this.AdminData.subid == params.subId) {
            this.isEdit1 = false;
            return;
          }
          this.isConfirmLoading = true;
          this.$api.systemManagement
            .EditManagerInfo(params)
            .then((res) => {
              this.isConfirmLoading = false;
              if (res.data.status == 200) {
                if (this.userInfo.isadmin) {
                  this.$confirm("切换成功,请重新登录", "提示", {
                    confirmButtonText: "确定",
                    showCancelButton: false,
                    closeOnClickModal: false,
                    showClose: false,
                    type: "success",
                  }).then(() => {
                    quitFun();
                  });
                } else {
                  this.$message({ message: "切换成功,请联系管理员重新登录", type: "success" });
                  this.getAdminMessage();
                }
              }
              // else{
              //   this.$message({ message: res.data.message, type: 'warning' });
              // }
            })
            .catch((err) => {
              this.isConfirmLoading = false;
            });
        }
      });
    },
  },
  created() {
    this.getJurisdiction();
    this.getUnitInfo();
    this.getAdminMessage();
    this.getindustryidList();
  },
  mounted() {
    this.watermark = this.userInfo.isOpenWatermark;
  },
  mixins: [mixinsMethod],
};
</script>

<style lang="less">
#unitInformation {
  padding: 0;

  // .consumptionDetails {
  //   position: relative;
  //   left: 20px;
  // }
  // .pageHead {
  //   height: 60px;
  //   line-height: 60px;
  //   border-bottom: 1px solid #edecf6;
  //   padding: 0 25px;
  //   .editBtnContent {
  //     height: 100%;
  //     line-height: 60px;
  //   }
  // }
  .pageMain {
    height: calc(100% - 20px);

    .unitForm {
      padding: 5px 25px 0 25px;
      font-size: 14px;

      .el-form-item {
        margin-right: 40px;

        .el-form-item__label {
          color: #333;
        }
      }

      .el-input {
        width: 180px;
      }

      .el-cascader {
        .el-input {
          width: 350px;
        }
      }

      .formheader {
        .el-form-item {
          display: inline-block;
        }
      }

      .formFooter {
        .el-form-item {
          display: inline-block;
        }
      }
    }

    .formHead {
      padding: 10px 20px;
      background: #f9faff;
      margin-bottom: 25px;

      .iconsize {
        font-size: 18px;
        float: right;
        margin-right: 10px;
        cursor: pointer;
      }
    }
  }

  .pageFooter {
    text-align: center;
    float: right;
  }
}
.popper_person {
  .el-cascader-panel {
    .el-scrollbar:first-child {
      .el-radio {
        display: none;
      }
      .el-checkbox {
        display: none;
      }
    }
  }
}
</style>
